﻿using MiniExcelLibs.OpenXml;
using MiniExcelLibs;
using AutoMapper;
using Prism.Events;
using System.IO;
using Newtonsoft.Json;
using Prism.Services.Dialogs;

namespace OP10.ViewModels
{
    public class AlarmsManagerViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IMapper _mapper;
        private readonly IEventAggregator _eventAggregator;
        private readonly IDialogService _dialogService;

        public AlarmsManagerViewModel(IRegionManager regionManager, IMapper mapper, IEventAggregator eventAggregator,IDialogService  dialogService)
        {
            _regionManager = regionManager;
            _dialogService = dialogService;
            _eventAggregator = eventAggregator;
            _mapper = mapper;
            GetWarningConfigs4Excel(@".\Documents\OP10报警表.xlsx");
            //开启定时器任务
            DispatcherTimer dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Interval =  TimeSpan.FromMilliseconds(50);
            dispatcherTimer.Tick += OnTick;
            dispatcherTimer.Start();


            //清除10天前的报警
            FileWrite.CleanFile(10,"OP10");
        }

        public bool[] IsboolArr { get; set; } = new bool[4096];
        public List<WarningModel> warnings { get; set; } = new List<WarningModel>();
        public bool IsAlarmChange = true;
        private void OnTick(object? sender, EventArgs e)
        {

            for (int i = 0; i < Alarm_Global.Alarms.Length; i++)
            {

                if (Alarm_Global.Alarms[i] && !IsboolArr[i])
                {
                    IsboolArr[i] = true;
                    warnings.Add(new WarningModel()
                    {
                        Time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                        IsAlarm = true,
                        Addr=listWarnings[i].Addr,
                        Number = i,
                        WarningMessage = listWarnings[i].WarningMessage,
                    });
                    IsAlarmChange = true;
                }

                else if (!Alarm_Global.Alarms[i])
                {
                    IsboolArr[i] = false;
                    for (int ii = warnings.Count - 1; ii >= 0; ii--)
                    {
                        if (warnings[ii].Number == i)
                        {
                            //var str = JsonConvert.SerializeObject(warnings[ii]);
                            var str = $"编号:{warnings[ii].Number} 地址:{warnings[ii].Addr} 报警内容:{warnings[ii].WarningMessage} 时间:{warnings[ii].Time}";
                            FileWrite.WriteFile(str,"OP10");
                            warnings.RemoveAt(ii);
                            IsAlarmChange = true;
                        }
                       
                    }
                }
            }
            if (IsAlarmChange)
            {
                ObWarnings = new ObservableCollection<WarningModel>(warnings);
                _eventAggregator.GetEvent<EventWarning>().Publish(ObWarnings);
            }
            IsAlarmChange = false;
        }




        #region 按钮命令


        private DelegateCommand _GoBackCommand;

        public DelegateCommand GoBackCommand =>
            _GoBackCommand ?? (_GoBackCommand = new DelegateCommand(ExecuteGoBackCommand));

        void ExecuteGoBackCommand()
        {
            _regionManager.RequestNavigate(PrismManager.MainViewRegionName, AppViews.MenuView);
        }

        private DelegateCommand _AlarmsHistoryCmd;
        public DelegateCommand AlarmsHistoryCmd =>
            _AlarmsHistoryCmd ?? (_AlarmsHistoryCmd = new DelegateCommand(ExecuteAlarmsHistoryCmd));

        void ExecuteAlarmsHistoryCmd()
        {
            DialogParameters keyValuePairs = new DialogParameters();
            _dialogService.ShowDialog("AlarmsHistoryView", keyValuePairs, callback =>
            {
                if (callback.Result == ButtonResult.OK)
                {
                    
                }
            });
        }

        #endregion



        #region 属性

        private ObservableCollection<WarningModel> _ObWarnings;
        public ObservableCollection<WarningModel> ObWarnings
        {
            get { return _ObWarnings ?? (_ObWarnings = new ObservableCollection<WarningModel>()); }
            set { SetProperty(ref _ObWarnings, value); }
        }
        #endregion


        #region function

        public List<WarningModel> listWarnings { get; set; } = new List<WarningModel>();
        private void GetWarningConfigs4Excel(string path)
        {
            //查询所有sheet
            var sheetNames = MiniExcel.GetSheetNames(path);
            var config = new OpenXmlConfiguration()
            {
                FillMergedCells = true,
            };

            foreach (var sheetName in sheetNames)
            {
                if (sheetName == "Alarms")
                {
                    var list = MiniExcel.Query<WarningExcelDto>(path, sheetName, configuration: config).ToList();
                    listWarnings = _mapper.Map<List<WarningModel>>(list);

                }
            }
        }
        #endregion
    }
}
